package com.guoliang.eduService.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guoliang.eduService.entity.EduSubject;
import com.guoliang.eduService.entity.excel.ExcelObjectData;
import com.guoliang.eduService.entity.subject.OneSubject;
import com.guoliang.eduService.entity.subject.TwoSubject;
import com.guoliang.eduService.listener.SubjectExcelListener;
import com.guoliang.eduService.mapper.EduSubjectMapper;
import com.guoliang.eduService.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guoliang.service.exceptionHandler.MyException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Wrapper;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author leo
 * @since 2023-01-17
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void importSubjectData(MultipartFile file,EduSubjectService eduSubjectService) {
        try {
            InputStream in = file.getInputStream();
            EasyExcel.read(in, ExcelObjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException(20002,"添加课程分类失败");
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubjects() {
        //查询所有一级分类
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("parent_id","0");
        List<EduSubject> oneSubjects = baseMapper.selectList(wrapper);
        //查询所有二级分类
        QueryWrapper<EduSubject> wrapper1=new QueryWrapper<>();
        wrapper1.ne("parent_id","0");
        List<EduSubject> twoSubjects = baseMapper.selectList(wrapper1);
        //封装
        List<OneSubject> finalList=new ArrayList<>();
        for (EduSubject e :
                oneSubjects) {
            OneSubject oneSubject=new OneSubject(e.getId(),e.getTitle());
            for (EduSubject child:twoSubjects) {
                if (child.getParentId().equals(oneSubject.getId())){
                    oneSubject.childrenPut(new TwoSubject(child.getId(),child.getTitle()));
                }
            }
            finalList.add(oneSubject);
        }
        return finalList;
    }
}
